using System.Drawing;
using System.IO;
using System.Threading.Tasks;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Extensions;
using Abp.IO;
using Abp.Runtime.Session;
using Abp.Timing;
using Abp.UI;
using KDS.Mes.Users.Profile.Dto;
using KDS.Mes.Configuration;
using KDS.Mes.Security;
using Newtonsoft.Json;
using KDS.Mes;
using KDS.Mes.Users.Profile;
using System;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security.DataProtection;
using Microsoft.AspNet.Identity.Owin;

namespace KDS.Mes.Users.Profile
{
    [AbpAuthorize]
    public class ProfileAppService : MesAppServiceBase, IProfileAppService
    {

        public ProfileAppService()
        {
        }

        public async Task ResetPassword(long userId)
        {
            var provider = new DpapiDataProtectionProvider("Mes");
            UserManager.UserTokenProvider = new DataProtectorTokenProvider<User, long>(provider.Create("UserToken"))
                as IUserTokenProvider<User, long>;

            string resetToken = await UserManager.GeneratePasswordResetTokenAsync(userId);
            IdentityResult passwordChangeResult = await UserManager.ResetPasswordAsync(userId, resetToken, "123qwe");
        }

        

        public async Task ChangePassword(ChangePasswordInput input)
        {
            await CheckPasswordComplexity(input.NewPassword);

            var user = await GetCurrentUserAsync();
            CheckErrors(await UserManager.ChangePasswordAsync(user.Id, input.CurrentPassword, input.NewPassword));
        }

        public async Task<GetPasswordComplexitySettingOutput> GetPasswordComplexitySetting()
        {
            var settingValue = await SettingManager.GetSettingValueAsync(AppSettings.Security.PasswordComplexity);
            var setting = JsonConvert.DeserializeObject<PasswordComplexitySetting>(settingValue);

            return new GetPasswordComplexitySettingOutput
            {
                Setting = setting
            };
        }

        private async Task CheckPasswordComplexity(string password)
        {
            var passwordComplexitySettingValue = await SettingManager.GetSettingValueAsync(AppSettings.Security.PasswordComplexity);
            var passwordComplexitySetting = JsonConvert.DeserializeObject<PasswordComplexitySetting>(passwordComplexitySettingValue);
            var passwordComplexityChecker = new PasswordComplexityChecker();
            var passwordValid = passwordComplexityChecker.Check(passwordComplexitySetting, password);
            if (!passwordValid)
            {
                throw new UserFriendlyException(L("PasswordComplexityNotSatisfied"));
            }
        }
    }
}